import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// flutter通过运行js代码向h5页面传递数据
const String htmlStr = '''
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>flutter通过运行js代码向h5页面传递数据</title>
  <script type="text/javascript">
    function hiCallJs(msg){
      document.getElementById('resultTxt').innerHTML = 'Flutter传递过来的数据：' + msg;
    }
    function hiCallJsWithResult(v1,v2){
      return parseInt(v1) + parseInt(v2);
    }
  </script>
</head>
<body>
  <div id="resultTxt" style="font-size: 2.5em">这里展示flutter传递过来的数据</div>
</body>
</html>
''';

class Flutter2jsByRunjs extends StatefulWidget {
  const Flutter2jsByRunjs({super.key});

  @override
  State<Flutter2jsByRunjs> createState() => _Flutter2jsByRunjsState();
}

class _Flutter2jsByRunjsState extends State<Flutter2jsByRunjs> {
  late WebViewController controller;

  get _fireData => FilledButton(onPressed: () async {
    String name = 'ccflutter';
    // 调用没有返回的函数
    controller.runJavaScript("hiCallJs('$name')");
    // 有返回的函数
    var res = await controller.runJavaScriptReturningResult("hiCallJsWithResult(1,2)");
    print('调用js函数的响应结果是：$res');
  }, child: Text('发送数据', style: TextStyle(color: Colors.white),));

  get _loadBtn => FilledButton(onPressed: (){
    controller.loadHtmlString(htmlStr);
  }, child: const Text(
    '加载h5页面',style: const TextStyle(color: Colors.white)
  ));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('flutter调用js函数传递数据'),
        actions: [ _loadBtn,_fireData ],
      ),
      body: WebViewWidget(controller: controller),
    );
  }

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }
}
